package com.sailing.xjpb.web.base.advice;

import com.sailing.xjpb.common.web.ActionResult;
import com.sailing.xjpb.common.web.translate.TranslateHandler;
import com.sailing.xjpb.common.web.translate.annotation.Translate;
import com.sailing.xjpb.common.web.translate.impl.DelegateTranslateHandler;
import com.sailing.xjpb.web.base.utils.SpringBean;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 返回值类型为{@linkplain ActionResult}的元素进行字典翻译
 * </p>
 * 目前支持翻译的对象：普通VO、page、Collection
 * </p>
 * 如果是其他数据结构，需要扩展本类代码。
 *
 * @author YW
 * @see TranslateHandler
 * @see Translate
 */
@Slf4j
@Order
@ControllerAdvice
public class TranslateResponseAdvisor implements ResponseBodyAdvice<Object> {

    @Autowired
    private DelegateTranslateHandler delegateTranslateHandler;

    @Override
    public boolean supports(@NonNull MethodParameter returnType,
                            @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, @NonNull MethodParameter returnType,
                                  @NonNull MediaType selectedContentType,
                                  @NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  @NonNull ServerHttpRequest request,
                                  @NonNull ServerHttpResponse response) {

        if (!(body instanceof ActionResult)) {
            return body;
        }

        // 初始化翻译处理器
        initTranslateHandlers();

        ActionResult<?> actionResult = (ActionResult<?>) body;
        if (actionResult.isSuccess()) {
            StopWatch clock = new StopWatch(request.getURI().getPath());
            clock.start("VO翻译");
            delegateTranslateHandler.doTranslate(actionResult.getResult());
            clock.stop();
            if (log.isDebugEnabled()) {
                log.debug(clock.prettyPrint());
            }
        }
        return actionResult;

    }

    /**
     * 初始化翻译处理器
     */
    private void initTranslateHandlers() {
        if (delegateTranslateHandler.getTranslateHandlers().isEmpty()) {
            synchronized (this) {
                if (delegateTranslateHandler.getTranslateHandlers().isEmpty()) {
                    List<TranslateHandler> translateHandlers = getTranslateHandlers();
                    delegateTranslateHandler.addAll(translateHandlers);
                }
            }
        }
    }

    /**
     * 初始化系统所有的翻译处理器
     */
    private List<TranslateHandler> getTranslateHandlers() {
        Collection<TranslateHandler> values = SpringBean.getBeans(TranslateHandler.class);
        return values.stream().sorted(Comparator.comparingInt(Ordered::getOrder)).collect(Collectors.toList());
    }
}
